/**
 * bootstrap-table工具类
 */
function Table(options) {
    this.options = $.extend({
        tableBox: "#tablelist"
    }, options);
}

String.prototype.replaceAll  = function(s1,s2){
    return this.replace(new RegExp(s1,"gm"),s2);
};

//发送图片的base64
function decode64(imgUrl){
    $.ajax({
        type: 'post',
        url: "/render/productManager/getImage",
        dataType: "json",
        data : {
            urls : imgUrl
        },
        success: function (data) {
            if(data.success){
                imgUrl = data.message;
                console.log(imgUrl);
            } else{
                console.log(data.message);
            }
        },
        error: function () {
            console.log("error!");
        }
    });
    return imgUrl;
}

function isBase64(str){
    if (str.startsWith('data:image')){
        return true;
    }else{
        return false;
    }
}

function getJsonValue(obj,name){
    var result = null;
    var value  = null;
    for(var key in obj){
        value = obj[key];
        if(key === name){
            return value;
        }
        if( key === "sub_images" ){
            value=JSON.stringify(value);
            value=JSON.parse(value);
            var flag=true;
            var flag_name=false;
            var str='';
            for (var key in value) {
                if(value[key]==='"'){
                    if (flag) {    //true  第一次
                        flag=!flag;   //false
                        continue ;
                    }
                    if (!flag){    //false  第二次
                        if (flag_name) {
                            return result=str;
                        }

                        if (name===str) {
                            flag_name=!flag_name;
                        }

                        str='';
                        flag=!flag;   //true
                        continue ;
                    }
                }
                if (!flag) {     //falg=false    第二次
                    str=str+value[key];
                }
            }
        }
    }
    return result;
}

function postParams(url,onExpandRow,options,rowStyle,mycolumns,searchtext,judge){
    // var searchText=JSON.stringify(searchtext);
    // console.log(""+searchtext);
    $("#tablelist").bootstrapTable('destroy').bootstrapTable({
        url: url,
        method: 'post',                      //请求方式（*）
        toolbar: '',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        contentType: "application/x-www-form-urlencoded", // 发送到服务器的数据编码类型, application/x-www-form-urlencoded为了实现post方式提交
        dataField: "rows",
        sortable: true,                     //是否启用排序
        // sortOrder: "asc",                   //排序方式
        sortStable: true,                   // 设置为 true 将获得稳定的排序
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 7,                       //每页的记录行数（*）
        queryParamsType:'',
        onSort:function(name,order) {
            $('#table').bootstrapTable('refreshOptions', {
                sortName:name,
                sortOrder:order
            });
        },
        queryParams: function queryParam(options){
            var param = {
                pageNumber: options.pageNumber,
                pageSize: options.pageSize,
                searchText: searchtext,
                sortName:this.sortName,
                sortOrder:this.sortOrder
            };
            return param;
        },
        pagination: judge,                   //是否显示分页（*）
        sidePagination:"server",           //分页方式：client客户端分页，server服务端分页（*）
        pageList: [7, 10, 15, 20, 25],        //可供选择的每页的行数（*）
        minimumCountColumns: 1,             //最少允许的列数
        iconsPrefix: 'fa',
        icons: {
            refresh: 'fa-refresh icon-refresh',
            toggle: 'fa-list-alt icon-list-alt',
            columns: 'fa-th icon-th',
            detailClose: 'fa-minus icon-minus'
        },
        height: 478,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
        onLoadSuccess: function () {
            console.log("table加载完成");
        },
        onExpandRow: onExpandRow,
        rowStyle: rowStyle || function (row, index) {
            return {};
        },
        columns: mycolumns,
        responseHandler:function(res){
            return {
                total : res.total, //总页数,前面的key必须为"total"
                rows : res.rows //行数据，前面的key要与之前设置的dataField的值一致.
            };
        }
    });
}

function modle_hide(){
    $("#addOrUpdateModal").css("display","");
    $("#addOrUpdateModal").removeClass("in");
    $(".modal-backdrop").removeClass("in");
}

function modle_show(){
    $("#addOrUpdateModal").css("display","block");
    $("#addOrUpdateModal").addClass("in");
    $(".modal-backdrop").addClass("in");
}

function modle_hide_comment(){
    $("#addOrUpdateModalByComment").css("display","");
    $("#addOrUpdateModalByComment").removeClass("in");
    $(".modal-backdrop-comment").removeClass("in");
}

function modle_show_comment(){
    $("#addOrUpdateModalByComment").css("display","block");
    $("#addOrUpdateModalByComment").addClass("in");
    $(".modal-backdrop-comment").addClass("in");
}


function fn_browse(){
    $('#main_image').trigger('click');
}

function fn_browse_image(){
    $('#image').trigger('click');
}

function fn_browse_cover_image(){
    $('#cover_image').trigger('click');
}

function fn_browse_left(){
    $('#image_left').trigger('click');
}

function fn_browse_center(){
    $('#image_center').trigger('click');
}

function fn_browse_right(){
    $('#image_right').trigger('click');
}

// var array = new Array(10);
Table.prototype = {
    init: function (callback) {
        this.createTable();
        this.bindBtnEvent(callback);
        return this;
    },
    createTable: function () {
        var options = this.options;
        postParams(options.url,options.onExpandRow,options,options.rowStyle,options.columns,null,true);
    },
    bindBtnEvent: function (callback) {
        var $table = this;
        var options = this.options;

        /* 添加 */
        $("#btn_add").unbind('click').click(function () {
            $table.resetForm();
            var $modal = $("#addOrUpdateModal");
            modle_show();
            // var file = document.getElementById('main_image');
            // file.value = ''; //虽然file的value值不能设为有内容的字符，但是可以设置为空字符
            $("#img_url").attr("src","");
            $("#image_url").attr("src","");
            $("#img_left_url").attr("src","");
            $("#img_center_url").attr("src","");
            $("#img_right_url").attr("src","");
            // $modal.modal('show');
            $modal.find(".modal-dialog .modal-content .modal-header .modal-title").html("添加" + options.modalName);

            var $password = $("#password");
            if ($password && $password[0]) {
                $password.attr("required", "required");
            }
            var $username = $("#username");
            if ($username && $username[0]) {
                $username.removeAttr("readonly");
            }


            if ($('#main_image').length > 0) {
                $('#main_image').parents('form').attr('enctype', 'multipart/form-data');
            }
            if ($('#image').length > 0) {
                $('#image').parents('form').attr('enctype', 'multipart/form-data');
            }
            if ($('#cover_image').length > 0) {
                $('#cover_image').parents('form').attr('enctype', 'multipart/form-data');
            }

            Table.prototype.bindSaveInfoEvent(options.createUrl, callback);
        });

        /* 修改 */
        this.bindClickEvent('.btn-update', function () {
            var $this = $(this);
            var userId = $this.attr("data-id");
            $.ajax({
                type: "post",
                url: options.getInfoUrl.replace("{id}", userId),
                success: function (json) {
                    if(json.success === 'false') {
                        $.alert.error(json.message);
                        return;
                    }

                    var info = json.message;
                    $table.resetForm(info);

                    modle_show();
                    /*var file = document.getElementById('main_image');
                    file.value = ''; //虽然file的value值不能设为有内容的字符，但是可以设置为空字符
                    $("#img_url").attr("src","");
                    file = document.getElementById('image_left');
                    file.value = '';
                    $("#img_left_url").attr("src","");
                    file = document.getElementById('image_center');
                    file.value = '';
                    $("#img_center_url").attr("src","");
                    file = document.getElementById('image_right');
                    file.value = '';
                    $("#img_right_url").attr("src","");*/

                    $("#addOrUpdateModal").find(".modal-dialog .modal-content .modal-header .modal-title").html("修改" + options.modalName);

                    // var $password = $("#password");
                    // if ($password && $password[0]) {
                    //     $password.removeAttr("required");
                    // }
                    // var $username = $("#username");
                    // if ($username && $username[0]) {
                    //     $username.attr("readonly", "readonly");
                    // }

                    if ($('#main_image').length > 0) {
                        $('#main_image').parents('form').attr('enctype', 'multipart/form-data');
                    }

                    if ($('#image').length > 0) {
                        $('#image').parents('form').attr('enctype', 'multipart/form-data');
                    }

                    if ($('#cover_image').length > 0) {
                        $('#cover_image').parents('form').attr('enctype', 'multipart/form-data');
                    }

                    Table.prototype.bindSaveInfoEvent(options.updateUrl, callback);
                },
                error: $.alert.ajaxError
            });
        });


        this.bindClickEvent('.btn-push', function () {
            var $this = $(this);
            var orderNo = $this.attr("data-id");
            /*$.ajax({
                type: "get",
                url: '/render/orderItemManager',
                success: function () {
                    $("#search-order_no").val(orderNo);

                },
                error: $.alert.ajaxError
            });*/

            window.location.href = '/render/orderitemManager?flag=true&order_no='+orderNo;

            /*$.ajax({
                type: "post",
                url: options.getInfoUrl.replace("{id}", orderNo),
                success: function (json) {
                    $.alert.ajaxSuccess(json);
                },
                error: $.alert.ajaxError
            });*/
        });

        this.bindClickEvent('.btn-reply', function () {
            var $this = $(this);
            var userId = $this.attr("data-id");
            $.ajax({
                type: "post",
                url: options.getInfoUrlByComment.replace("{id}", userId),
                success: function (json) {
                    if(json.success === 'false') {
                        $.alert.error(json.message);
                        return;
                    }

                    var info = json.message;
                    $table.resetFormByComment(info);

                    modle_show_comment();
                    $("#addOrUpdateModalByComment").find(".modal-dialog .modal-content .modal-header .modal-title").html("修改" + options.modalName);

                    Table.prototype.bindSaveInfoEvent(options.updateUrlByComment, callback);
                },
                error: $.alert.ajaxError
            });
        });

        /* 删除 */
        function remove(ids) {
            var len = 1;
            if(typeof ids == "object") {
                len = ids.length;
            }
            $.alert.confirm("确定删除已选中的" + len + "条 [ " + options.modalName + " ] 信息？", function () {
                $.ajax({
                    type: "post",
                    url: options.removeUrl,
                    traditional: true,
                    data: {'ids': ids},
                    success: function (json) {
                        $.alert.ajaxSuccess(json);
                        $table.refresh();
                    },
                    error: $.alert.ajaxError
                });
            }, function () {

            }, 5000);
        }

        /* 批量删除用户 */
        $("#btn_delete_ids").click(function () {
            var selectedId = $table.getSelectedIds();
            if (!selectedId || selectedId == '[]' || selectedId.length == 0) {
                $.alert.error("请至少选择一条记录");
                return;
            }
            remove(selectedId);
        });

        this.bindClickEvent('.btn-remove', function () {
            var $this = $(this);
            var userId = $this.attr("data-id");
            remove(userId);
        });
    },
    bindEvent: function(eventName, selector, callback){
        var options = this.options;
        $(options.tableBox).on(eventName, selector, callback);
    },
    bindClickEvent: function(selector, callback) {
        this.bindEvent("click", selector, callback);
    },
    refresh: function (optionsUrl) {
        // var options = this.options;
        // console.log("11111111111111");
        $("#tablelist").bootstrapTable('refresh', {url: optionsUrl});
    },
    bindSaveInfoEvent: function(url, callback) {
        var $table = this;
        var $form = $("#addOrUpdateForm"),
            $formByComment = $("#addOrUpdateFormByComment"),
            $submitBtn = $(".addOrUpdateBtn");
            $submitBtnByComment = $(".addOrUpdateBtnByComment");
        // $modal = $("#addOrUpdateModal");
        $submitBtn.unbind('click');
        $submitBtnByComment.unbind('click');
        callback && callback();
        $submitBtn.click(function () {
            if ($('#editor').length > 0) {
                $('#editor').find("img").each(function(){
                    if (isBase64($(this).attr('src'))){
                        var imageABase64 = $(this).attr('src').replaceAll("\\+", "%2B");
                        $(this).attr("src",imageABase64);
                    }
                });
                $("#detail").val(editorText());
                /*if($(".product_editor").length>0){
                    //遍历一段html，获取img的url（base64），发送到后端，返回相对路径。
                    // console.log("product_editor");
                    $('#detail').find("img").each(function(){
                        if (isBase64($(this).attr('src'))){
                            $(this).attr("src",decode64($(this).attr('src')));
                            $(this).css("width", "65%");
                            $(this).css("height", "65%");
                        }else {
                            for (var index=0;index<array.length;index++){
                                if ($(this).attr('src')==array[index]){
                                    array[index]="";
                                }
                            }
                        }
                    });

                    $("#detail").val(editorText());
                }else{
                    $('#editor').find("img").each(function(){
                        if (isBase64($(this).attr('src'))){
                            var imageABase64 = $(this).attr('src').replaceAll("\\+", "%2B");
                            // console.log("imageABase64"+$(this).attr('src'));
                            // imageABase64 = encodeURIComponent(imageABase64);
                            $(this).attr("src",imageABase64);
                            // console.log("news"+imageABase64);
                        }
                    });
                    // console.log("news"+editorText());
                    $("#detail").val(editorText());
                    console.log($("#detail").val());
                }*/
            }

            // if (validator.checkAll($form)) {
                if ($table.isMultipartForm($form)) {
                    $form.ajaxSubmit({
                        type: 'post',
                        url: url,
                        success: function (json) {
                            // console.log("第一个");
                            $.alert.ajaxSuccess(json);
                            modle_hide();
                            $table.refresh();

                            $("#addOrUpdateForm_before").css("display","");
                            $("#addOrUpdateForm_after").css("display","none");
                            $(".addOrUpdateBtn_before").css("display","none");
                            $(".addOrUpdateBtn_next").css("display","");
                            // $(".addOrUpdateBtn").css("display","");
                            $(".addOrUpdateBtn_close").css("display","");
                        },
                        error: $.alert.ajaxError
                    });
                } else {
                    $.ajax({
                        type: "post",
                        url: url,
                        data: $form.serialize(),
                        success: function (json) {
                            $.alert.ajaxSuccess(json);
                            modle_hide();
                            $table.refresh();

                            $("#addOrUpdateForm_before").css("display","");
                            $("#addOrUpdateForm_after").css("display","none");
                            $(".addOrUpdateBtn_before").css("display","none");
                            $(".addOrUpdateBtn_next").css("display","");
                            // $(".addOrUpdateBtn").css("display","");
                            $(".addOrUpdateBtn_close").css("display","");
                        },
                        error: $.alert.ajaxError
                    });
                }
            // }
        });
        $submitBtnByComment.click(function () {
            $.ajax({
                type: "post",
                url: url,
                data: $formByComment.serialize(),
                success: function (json) {
                    $.alert.ajaxSuccess(json);
                    modle_hide_comment();
                    $table.refresh();

                    $("#addOrUpdateForm_before").css("display","");
                    $("#addOrUpdateForm_after").css("display","none");
                    $(".addOrUpdateBtn_before").css("display","none");
                    $(".addOrUpdateBtn_next").css("display","");
                    // $(".addOrUpdateBtn").css("display","");
                    $(".addOrUpdateBtn_close").css("display","");
                },
                error: $.alert.ajaxError
            });
        });
    },
    getSelectedIds: function () {
        var selectedJson = this.getSelections();
        var ids = [];
        $.each(selectedJson, function (i) {
            ids.push(selectedJson[i].id);
        });
        return ids;
    },
    getSelections: function () {
        var options = this.options;
        return $(options.tableBox).bootstrapTable('getAllSelections')
    },
    isMultipartForm: function (form) {
        var $form = $(form),
            enctype = $form.attr("enctype");
        return enctype && enctype === "multipart/form-data";
    },
    resetForm: function (info) {
        var $table = this;
        //每个被选中的id选择器都可以进行遍历，没有就不遍历。
        $("#addOrUpdateModal form input,#addOrUpdateModal form select,#addOrUpdateModal form textarea").each(function () {
            var $this = $(this);
            $table.clearText($this, this.type, info);
        });
    },
    resetFormByComment: function (info) {
        var $table = this;
        //每个被选中的id选择器都可以进行遍历，没有就不遍历。
        $("#addOrUpdateModalByComment form input,#addOrUpdateModalByComment form select,#addOrUpdateModalByComment form textarea").each(function () {
            var $this = $(this);
            $table.clearText($this, this.type, info);
        });
    },
    clearText: function ($this, type, info) {
        //固定不变的，就不用再赋值。
        if($this.hasClass("final") || $this.data("final")) {
            return;
        }

        // console.log("111111");

        var $div = $this.parents(".item");
        if ($div && $div.hasClass("bad")) {
            $div.removeClass("bad");
            $div.find("div.alert").remove();
        }
        //data不为空，那么就一直循环下去。
        if (info) {
            var thisName = $this.attr("name");
            //如果没有name的就不用赋值
            if (("undefined" == typeof thisName)) {
                return;
            }
            var thisValue;

            // console.log("222222");
            //判断name是否合法
            if (thisName.indexOf(".") !== -1) {
                var nodeObj = info[thisName.split(".")[0]];
                if (nodeObj) {
                    thisValue = nodeObj[thisName.split(".")[1]];
                }
            } else {
                //从json格式中获取key为thisName的值。
                thisValue = info[thisName];
            }

            // console.log(thisValue);
            if (type === 'radio') {
                var _typeof = (typeof thisValue);
                if (_typeof === "boolean") {
                    // $this.iCheck(((thisValue && 1 === $this.val()) || (!thisValue && 0 === $this.val())) ? 'check' : 'uncheck');
                    $this.val(thisValue);
                } else if (_typeof === "number") {
                    // $this.iCheck((thisValue === $this.val()) ? 'check' : 'uncheck');
                    $this.val(thisValue);
                } else if (_typeof === "string") {
                    if (thisValue === $this.val()) {
                        // $this.iCheck('check');
                        $this.val(thisValue);
                    } else {
                        // $this.iCheck('uncheck');
                        $this.val(thisValue);
                    }
                }
            } else if (type.startsWith('select')) {
                if (thisValue === 'true' || thisValue === true) {
                    thisValue = 1;
                } else if (thisValue === 'false' || thisValue === false) {
                    thisValue = 0;
                }
                // console.log(thisValue);
                $this.val(thisValue);
            } else {
                if(type === 'file') {
                    if (thisName ==='image'){
                        $("#image_url").attr("src",thisValue);
                    }
                    if (thisName ==='main_image'){
                        $("#img_url").attr("src",thisValue);
                    }
                    if (thisName === 'image_left') {
                        thisValue=getJsonValue(info,thisName);
                        thisValue=(thisValue==='null')?'':thisValue;
                        $('#image_left')[0].files[0]=thisValue;
                        $("#img_left_url").attr("src",thisValue);
                    }
                    if (thisName === 'image_center') {
                        thisValue=getJsonValue(info,thisName);
                        thisValue=(thisValue==='null')?'':thisValue;
                        $("#img_center_url").attr("src",thisValue);
                    }
                    if (thisName === 'image_right') {
                        thisValue=getJsonValue(info,thisName);
                        thisValue=(thisValue==='null')?'':thisValue;
                        $('#image_right')[0].files[0]=thisValue;
                        $("#img_right_url").attr("src",thisValue);
                    }

                    if (thisName === 'cover_image') {
                        thisValue=getJsonValue(info,thisName);
                        thisValue=(thisValue==='null')?'':thisValue;
                        $('#cover_image')[0].files[0]=thisValue;
                        $("#img_url").attr("src",thisValue);
                    }
                } else if (type === 'password') {
                    $this.val('');
                } else {
                    if (thisName === 'detail') {
                        editorContent(thisValue);
                        /*var i=0;
                        $('#editor').find("img").each(function(){
                            array[i++]=$(this).attr('src');
                        });*/
                    }else if (thisName === 'content_url') {
                        editorContent(thisValue);
                    }else{
                        $this.val(thisValue);
                    }
                }
            }
        } else {
            // console.log("333333");
            if (type === 'radio' || type === 'checkbox') {
                // $this.iCheck('uncheck');
                $this.val('');
            } else if (type === 'file') {
                $this.val('');
            } else {
                $this.val('');
            }
        }
    }
};




// //是否有对象属性
// function isHasAttr(obj, attr) {
//     //判断是否有该键值
//     if (obj && obj.hasOwnProperty(attr)) {
//         //如果有返回true
//         return true;
//     }
//     return false;
// }
//
// //是否含有对象属性对应的值
// function isHasAttrVal(obj, attr, value) {
//     //判断是否有该键值对应的值
//     if (obj && obj.hasOwnProperty(attr) && obj[attr] === value) {
//         //如果有返回true
//         return true;
//     }
//     return false;
// }

// for (var index=0;index<array.length;index++){
//     if (array[index] != "") {
//         console.log(index+""+array[index]);
//     }
// }